<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      label-width="80px"
      class="frominfo"
    >
      <!-- 搜索栏部分 -->
      <div class="from-item">
        <el-form-item label="参数名" prop="variableName">
          <el-select
            v-model="queryParams.variableId"
            placeholder="请下拉选择"
            clearable
            :style="{ width: '100%' }"
          >
            <el-option
              v-for="(item, index) in paramsList"
              :key="index"
              :label="item.variableName"
              :value="item.variableId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否已填">
          <el-select
            v-model="queryParams.isPush"
            placeholder="请下拉选择"
            clearable
            :style="{ width: '100%' }"
          >
            <el-option
              v-for="(item, index) in itemList"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属人员" v-if="!common" prop="nickName">
          <el-input v-model="queryParams.nickName" @keyup.enter.native="handleQuery" placeholder="请输入所属人员" clearable/>
        </el-form-item>
        <el-form-item label="在群助手" prop="wcName" v-if="!common">
          <el-select style="width: 120px;" v-if="!qommon"
                     v-model="queryParams.deptId"
                     @change="getDept"
                     placeholder="请选择区域"
                     clearable
          >
            <el-option
              v-for="dict in deptName"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
          <el-autocomplete style="width: 160px;"
                           class="my-autocomplete"
                           v-model="param.lable"
                           :fetch-suggestions="querySearch"
                           placeholder="请输入内容"
                           @select="handleSelect"
          ></el-autocomplete>
        </el-form-item>
      </div>
      <div class="from-Btn">
        <el-form-item>
          <el-button
            class="blue-button"
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleQuery"
            >查询</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
            >重置</el-button
          >
        </el-form-item>
      </div>
    </el-form>

    <el-row :gutter="10">
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="derive"
          style="margin-bottom: 10px"
          >导出</el-button
        >
      </el-col>
    </el-row>

    <el-table :data="tableData" style="width: 100%">
      <el-table-column label="变量名称" prop="variableName"></el-table-column>
      <el-table-column label="真实姓名" prop="nickName"></el-table-column>
      <el-table-column label="地区" prop="deptName"></el-table-column>
      <el-table-column label="是否已填">
        <template slot-scope="scope">
          {{ scope.row.isPush == 1 ? "已填" : "未填" }}
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            v-if="scope.row.isPush == 1"
            @click="handleUpdate(scope.row)"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            v-if="scope.row.isPush == 1"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            v-if="scope.row.isPush == 0"
            @click="handleAdd(scope.row)"
            >新增</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="变量名称" prop="variableName">
          <el-input
            disabled
            v-model="form.variableName"
            placeholder="请输入变量名称"
          />
        </el-form-item>
        <el-form-item label="变量值" prop="variableName">
          <el-input
            :disabled="form.variableType == 3 || form.variableType == 4"
            v-model="form.variableValue"
            placeholder="请输入变量值"
          />
        </el-form-item>
        <el-form-item
          label="上传"
          prop="variableDescribe"
          required
          v-if="form.variableType == 3 || form.variableType == 4"
        >
          <el-upload
            ref="variableDescribeRef"
            :file-list="variableDescribeList"
            :action="variableDescribeAction"
            :before-upload="variableDescribeBeforeUpload"
            :on-success="handleFileSuccess"
            :headers="headers"
          >
            <el-button size="small" type="primary" icon="el-icon-upload"
              >点击上传</el-button
            >
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="confirm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script>
import {
  adminReadParamsDetail,
  adminReadParams,
  adminEditParamsDetail,
  adminAddParamsDetail,
  adminDelParamsDetail,
  adminExportParamsDetail,
} from "@/api/system/params";
import { getToken } from "@/utils/auth";
import {listWcUser} from "@/api/system/user";
import { listDept } from "@/api/system/dept";

export default {
  data() {
    return {
      tableData: [],
      total: 0,
      form: {},
      rules: {
        variableName: [
          { required: true, message: "变量名称不能为空", trigger: "blur" },
        ],
      },
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        variableId: "",
        variableName: "",
        isPush: "",
        deptId: "",
        wcId: "",
        nickName:"",
      },
      param:{
        wcId: null,
        lable:null,
      },
      deriveParams: {
        variableId: "",
        variableName: "",
        isPush: "",
      },
      itemList: [
        {
          label: "已填",
          value: 1,
        },
        {
          label: "未填",
          value: 0,
        },
      ],
      userParams: {
        pageNum: 1,
        pageSize: 9999,
        deptId: undefined,
      },
      labelName:[],
      deptName:[],
      qommon:false,
      common:false,
      paramsList: [],
      title: "",
      open: false,
      isChange: true,
      variableDescribeList: [],
      headers: { Authorization: "Bearer " + getToken() },
      variableDescribeAction: process.env.VUE_APP_BASE_API + "/common/upload",
    };
  },
  mounted() {
    this.getList();
    this.getParamsList();
  },
  created() {
    if (this.$store.state.user.roles.includes("common")) {
      this.common = true;
      this.qommon=true;
    }
    if (this.$store.state.user.roles.includes("qxleader")) {
      this.common = false;
      this.qommon=true;
    }
    if(!this.qommon){
      var deptName=[]
      listDept().then(response => {
        if(response.code==200){
          response.data.forEach((item) =>{
            deptName.push({value:item.deptId,label:item.deptName})
          })
          this.deptName=deptName
        }
      });
    }else{
      var userName=[]
      this.userParams=null
      listWcAssist(this.userParams).then((res) => {
        if (res["success"]) {
          const dt = res["data"];
          dt["records"].forEach((element) => {
            //userName.push({value:element.wcId,label:element.wcName})
            userName.push({value:element.wcName,label:element.wcId})
          });
        }
        this.userName=userName
      });
    }
  },
  methods: {
    handleSelect(item) {
      this.param.lable=item.value
      this.queryParams.wcId=item.label
    },
    getDept(value) {
      if(value!=''){
        this.userParams.deptId=value
        this.queryParams.wcId=null
        var userName=[]
        listWcUser(this.userParams).then((res) => {
          //console.log(res)
          if (res["code"]==200) {
            const dt = res["rows"];
            dt.forEach((element) => {
              if(this.userParams.deptId==100){
                if(element.deptId==100&&element.wcId!=''&&element.wcId!=null){
                  // userName.push({value:element.wcId,label:element.nickName})
                  userName.push({value:element.nickName,label:element.wcId})
                }
              }else if(element.wcId!=''&&element.wcId!=null){
                // userName.push({value:element.wcId,label:element.nickName})
                userName.push({value:element.nickName,label:element.wcId})
              }
            });
          }
          this.userName=userName
        });
      }
    },
    querySearch(queryString, cb) {
      var restaurants = this.userName;
      var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    getList() {
      adminReadParamsDetail(this.queryParams).then((res) => {
        this.tableData = res.data.records;
        this.total = res.data.total;
      });
    },
    getParamsList() {
      adminReadParams().then((res) => {
        this.paramsList = res.data.records;
      });
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        variableId: "",
        variableName: "",
        isPush: "",
        wcId: "",
      };
      this.param = {
        wcId: null,
        lable:null,
      };
      this.getList();
    },
    derive() {
      this.deriveParams.variableId = this.queryParams.variableId;
      this.deriveParams.variableName = this.queryParams.variableName;
      this.deriveParams.isPush = this.queryParams.isPush;
      adminExportParamsDetail(this.deriveParams).then((res) => {
        var now = new Date();
        var year = now.getFullYear();
        var month = ("0" + (now.getMonth() + 1)).slice(-2);
        var day = ("0" + now.getDate()).slice(-2);
        var fileName = "助手变量信息" + year + month + day + ".xlsx";
        var blob = new Blob([res]);
        var downloadElement = document.createElement("a");
        var href = window.URL.createObjectURL(blob);
        downloadElement.href = href;
        downloadElement.download = fileName;
        document.body.appendChild(downloadElement);
        downloadElement.click();
        document.body.removeChild(downloadElement);
        window.URL.revokeObjectURL(href);
      });
    },
    handleAdd(row) {
      this.title = "新增变量";
      this.open = true;
      this.isChange = false;
      this.form = { ...row };
    },
    handleUpdate(row) {
      this.title = "修改变量";
      this.open = true;
      this.form = { ...row };
    },
    handleDelete(row) {
      this.$confirm(
        "是否确认删除变量名称为" + row.variableName + "的数据项?",
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).then(() => {
        adminDelParamsDetail({
          variableId: row.variableId,
          userId: row.userId,
        }).then((res) => {
          if (res.code == 200) {
            this.getList();
            this.$message.success("删除成功");
          }
        });
      });
    },
    cancel() {
      this.open = false;
    },
    confirm() {
      if (this.isChange) {
        adminEditParamsDetail(this.form).then((res) => {
          if (res.code == 200) {
            this.$message.success("修改成功");
            this.getList();
            this.open = false;
          }
        });
      } else {
        adminAddParamsDetail(this.form).then((res) => {
          if (res.code == 200) {
            this.$message.success("新增成功");
            this.getList();
            this.open = false;
            this.isChange = true;
          }
        });
      }
    },
    variableDescribeBeforeUpload(file) {
      let isRightSize = file.size / 1024 / 1024 < 2;
      if (!isRightSize) {
        this.$message.error("文件大小超过 2MB");
      }
      return isRightSize;
    },
    handleFileSuccess(response, file, fileList) {
      this.form.variableValue = response.url;
    },
  },
};
</script>
<style lang="scss">
.app-container {
  background-color: #f6f9fb;
}
.frominfo {
  display: flex;
  background-color: #fff;
  padding: 10px;
  padding-bottom: 0;
  margin-bottom: 20px;

  .from-item {
    display: flex;
    flex-wrap: wrap;
    width: 85%;
  }

  .from-Btn {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    width: 20%;
  }
}
.add-upload {
  display: flex;
  width: 400px;
  border-radius: 5px;
  border: 1px solid #dcdfe6;
  justify-content: center;
  align-items: center;
  padding: 20px 0;
  margin-left: 15px;
  margin-bottom: 20px;
}
</style>
